package com.coder4j.starter.tools.util;

import java.io.*;
import java.nio.file.*;
import java.util.zip.*;

/**
 * Zip压缩工具类
 * @author keller
 * @date 2025-05-26 19:39:39
 */
public class ZipUtil {

    public static void zipDirectory(String sourceDirPath, String zipFilePath) throws IOException {
        Path zipFile = Paths.get(zipFilePath);
        try (ZipOutputStream zs = new ZipOutputStream(new FileOutputStream(zipFile.toFile()))) {
            Path sourceDir = Paths.get(sourceDirPath);
            Files.walk(sourceDir)
                    .filter(path -> !Files.isDirectory(path))
                    .forEach(path -> {
                        ZipEntry zipEntry = new ZipEntry(sourceDir.relativize(path).toString());
                        try {
                            zs.putNextEntry(zipEntry);
                            Files.copy(path, zs);
                            zs.closeEntry();
                        } catch (IOException e) {
                            throw new RuntimeException("压缩文件失败: " + path, e);
                        }
                    });
        }
    }
}
